package com.xy6.jvm.threadpool.executors2;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

/**
 * @author zhang
 * @since
 */
public class CallbackMain1 {

	public static void main(String[] args) throws InterruptedException, ExecutionException {
		test1();
	}
	
	public static void test1() throws InterruptedException, ExecutionException{
		ExecutorService executor = Executors.newFixedThreadPool(2);
		//创建一个Callable，3秒后返回String类型
		Callable<String> myCallable = new Callable<String>() {
			@Override
			public String call() throws Exception {
				for(int i=0; i<15; i++){
					System.out.println(i);
					Thread.sleep(1000);
				}
				System.out.println("calld方法执行了");
				return "call方法返回值";
			}
		};
		System.out.println("提交任务之前 " + getStringDate());
		Future<String> future = executor.submit(myCallable);
		System.out.println("提交任务之后，获取结果之前 " + getStringDate());
		System.out.println("获取返回值: " + future.get());
		System.out.println("获取到结果之后 " + getStringDate());
	}

	/**
	 * 使用Future.cancel()，实现停止一个线程
	 * 
	 * @throws InterruptedException
	 */
	public static void test2() throws InterruptedException{
		ExecutorService executor = Executors.newFixedThreadPool(2);
		@SuppressWarnings("rawtypes")
		Future future2 = executor.submit(new Runnable(){
			@Override
			public void run(){
				for(int i=0; i<15; i++){
					System.out.println(i);
					try {
						Thread.sleep(1000);
					} catch (InterruptedException e) {
						e.printStackTrace();
						break;
					}
				}
			}
		});
		Thread.sleep(5000);
		future2.cancel(true);
		
		Thread.currentThread().join();
	}
	
	public static String getStringDate() {
		Date currentTime = new Date();
		SimpleDateFormat formatter = new SimpleDateFormat("HH:mm:ss");
		String dateString = formatter.format(currentTime);
		return dateString;
	}

}
